#include "serverwindow.h"
#include "ui_serverwindow.h"

ServerWindow::ServerWindow(QWidget *parent) :
    QMainWindow(parent),
    m_ui(new Ui::ServerWindow)
{
    m_ui->setupUi(this);
    server = new Server(true);
    disconnectedControlsState();
    connect(server, SIGNAL(connectionStateChanged(QAbstractSocket::SocketState)),this,SLOT(onServerStateChange(QAbstractSocket::SocketState)));
}

ServerWindow::~ServerWindow()
{
    qDebug() << "serv stop";
    server->stopServer();
    delete m_ui;
}

void ServerWindow::onStartServerClicked()
{

	if (server->state() == QAbstractSocket::UnconnectedState)
	{
		QVariant v(m_ui->edPort->text());
		bool *ok = new bool;
		int port = v.toInt(ok);
		if (*ok)
		{
			delete server;
			server = new Server(true);
			connect(server, SIGNAL(connectionStateChanged(QAbstractSocket::SocketState)),this,SLOT(onServerStateChange(QAbstractSocket::SocketState)));
			connect(server, SIGNAL(newPlayerConnected(ConnectionPlayer*)),m_ui->scoreTable, SLOT(addPlayer(ConnectionPlayer*)));
			connect(server, SIGNAL(playerDisconnected(ConnectionPlayer*)),m_ui->scoreTable, SLOT(removePlayer(ConnectionPlayer*)));
			server->startServer(port);
		}
		delete ok;
	}
	else
    {
        server->stopServer();
    }
}

void ServerWindow::connectedControlsState()
{
    m_ui->btnStartServer->setText("Stop Server");
    m_ui->edPort->setEnabled(false);
    m_ui->scoreTable->setEnabled(true);
}

void ServerWindow::disconnectedControlsState()
{
    m_ui->btnStartServer->setText("Start Server");
    m_ui->edPort->setEnabled(true);
    m_ui->scoreTable->setEnabled(false);
}

void ServerWindow::onServerStateChange(QAbstractSocket::SocketState state)
{
    switch (state)
    {
        case QAbstractSocket::UnconnectedState:
            m_ui->statusbar->showMessage("Unconnected");
            disconnectedControlsState();
        break;
        case QAbstractSocket::HostLookupState:
            m_ui->statusbar->showMessage("Host Lookup...");
        break;
        case QAbstractSocket::ConnectingState:
            m_ui->statusbar->showMessage("Connecting...");
        break;
        case QAbstractSocket::ConnectedState:
            m_ui->statusbar->showMessage("Connected");
            connectedControlsState();
        break;
        case QAbstractSocket::BoundState:
            m_ui->statusbar->showMessage("Bound");
            connectedControlsState();
        break;
        case QAbstractSocket::ClosingState:
            m_ui->statusbar->showMessage("Closing...");
        break;
        case QAbstractSocket::ListeningState:
            m_ui->statusbar->showMessage("Listening");
            connectedControlsState();
        break;
    }
}

void ServerWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
